package server;

/**
 * @author zyy
 * @date 2020/12/29 上午7:25
 * @description
 */

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.mapper.Context;
import server.mapper.Host;
import server.mapper.Mapper;
import server.mapper.Wrapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {
    /***
     * 定义socket监听的端口
     */
    private int port = 8080;

    /**
     * 映射实体对象
     * Mapper --> Host -->Context --> Wrapper
     */
    private Mapper mapper = new Mapper();



    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        //加载解析server.xml配置
        loadServer();

        //定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);

        /**
         完成Minicat1.0版本
         需求：浏览器请求http://localhost:8080，返回一个固定字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("====>>>Minicat start on port: " + port);

        /*while (true) {
            Socket socket = serverSocket.accept();
            //有了socket接收请求，获取输入流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成Minicat2.0版本
         * 需求：封装Request和Response对象 返回html静态资源文件
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();
        }*/

        /**
         * 完成Minicat3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //判断是静态资源还是动态资源（Servlet）
            //对静态资源进行处理
            if(servletMap.get(request.getUrl()) == null){
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            socket.close();
        }*/

        /**
         * 多线程改造 不使用线程池
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.start();
        }*/

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /**
         * 多线程改造 使用线程池
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    /**
     * 加载解析server.xml文件
     */
    private void loadServer() {
        //1.加载配置文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        //2.解析配置文件
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> serverElements = rootElement.selectNodes("//Server");
            if(serverElements == null || serverElements.isEmpty()){
                return;
            }
            Element serviceElement = serverElements.get(0).element("Service");
            Element connectorElement = serviceElement.element("Connector");
            //获取端口号
            port = Integer.parseInt(connectorElement.attribute("port").getText());
            //3.封装主机实体对象
            Element engineElement = connectorElement.element("Engine");
            List<Element> hostElements = engineElement.elements("Host");
            if(hostElements == null || hostElements.isEmpty()){
                return;
            }
            for (int i = 0; i < hostElements.size(); i++) {
                Element hostElement = hostElements.get(i);
                String hostName = hostElement.attribute("name").getText();
                String hostAppBase = hostElement.attribute("appBase").getText();
                List<Context> contexts = new ArrayList<Context>();
                //4.封装上下文实体对象
                File appBaseFile = new File(hostAppBase);
                if(!appBaseFile.exists() || !appBaseFile.isDirectory()){
                    continue;
                }
                File[] files = appBaseFile.listFiles();
                for (int j = 0; j < files.length; j++) {
                    File file = files[j];
                    if(file.isDirectory()){
                        String contextName = file.getName();
                        String contextAbsolutePath = file.getAbsolutePath();
                        Context context = new Context(contextName, contextAbsolutePath);
                        loadServlet(contextAbsolutePath,context);
                        contexts.add(context);
                    }
                    
                }
                Host host = new Host(hostName, hostAppBase, contexts);
                mapper.getHosts().add(host);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载解析web.xml文件，初始化Servlet
     * @param path 应用部署目录：demo1,demo2
     * @param context 应用上下文实例对象
     */
    private void loadServlet(String path, Context context) {
        try {
            InputStream resourceAsStream = new FileInputStream(path +"/web.xml" );
            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>myServlet</servlet-name>
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMappingElement = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name = '" + servletName + "']");
                //url
                String urlPattern = servletMappingElement.selectSingleNode("url-pattern").getStringValue();
                //获取servlet对象
                MyClassLoader myClassLoader = new MyClassLoader();
                Class<?> clazz = myClassLoader.findClass(path + File.separator, servletClass);
                Object o = clazz.newInstance();
                //封装Wrapper
//                Wrapper wrapper = new Wrapper(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
                Wrapper wrapper = new Wrapper(urlPattern, (Servlet) o);
                context.getWrappers().add(wrapper);

            }
        } catch (DocumentException  e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
